import md5Libs from "uview-ui/libs/function/md5";
import Tools from '@/utils/Tools.js'
import store from '@/store/index.js'
import { CLIENT } from '@/constant/Config.js';
const install = (Vue, vm) => {
	Vue.prototype.$u.http.setConfig({
		dataType: 'json',
		loadingText: '努力加载中~',
		showLoading: true,
		loadingTime: 1000,
		loadingMask: true,
		originalData: true
	});
	Vue.prototype.$u.http.interceptor.request = (config) => {
		console.log(config)
		const systemInfo = uni.getSystemInfoSync();
		const timestamp = Date.parse(new Date()) / 1000
		const data = config.data;
		const token = store.state.user.token
		if (data.auth == 'token' && !token) {
			// #ifndef MP
			Tools.toLoginPage();
			// #endif
		}
		data.sys = systemInfo.platform.toLowerCase();
		data._model = systemInfo.model;
		data._language = systemInfo.language;
		data._timestamp = timestamp;
		const keys = Object.keys(data).sort();
		const obj = {};
		for (let i = 0; i < keys.length; i++) {
			//遍历newkey数组
			obj[keys[i]] = data[keys[i]];
			//向新创建的对象中按照排好的顺序依次增加键值对
		}
		const str = Vue.prototype.$u.queryParams(data, 'true', 'comma');
		// md5Libs.
		data._sign = md5Libs.md5(md5Libs.md5(str) + timestamp);
		config.data = data;
		config.header = {
			'content-type': 'application/x-www-form-urlencoded',
			'Authorization': token || ('' + '||' + CLIENT),
			// 'Client': client
		}

		return config;
		// TODO 引用token
	}
	Vue.prototype.$u.http.interceptor.response = (response) => {
		if (response.errMsg == 'request:ok') {
			if (response.statusCode == 200) {
				const data = response.data;
				if (data.code == 200) {
					return data;
				} else {
					if (data.code == 102) {
						uni.showModal({
							title: '',
							content: '登录失效，请重新登录',
							showCancel: false,
							success: (res) => {
								Tools.logout().then(() => {
									Tools.toLoginPage();
								})
							}
						})

					} else if (data.code == 201) {
						uni.showToast({
							icon: 'none',
							title: `错误${data.code}：${data.msg}`
						})
					} else if (data.code == 404) {
						//TODO 需要升级
					} else if (data.code == 601) {
						uni.showModal({
							title: "友情提示",
							content: '实名认证后方可继续使用本系统哦。\n是否立即实名?',
							confirmText: '去实名',
							cancelText: '稍后',
							success: (e) => {
								if (e.confirm) {
									uni.navigateTo({
										url: '/pageUser/certification/input'
									})
								}
							}
						})
					}
					return false
				}
			} else if (response.statusCode == 404) {
				uni.showToast({
					icon: 'none',
					title: '404~相关服务不存在'
				})
				return false
			} else {
				uni.showToast({
					icon: 'none',
					title: '系统正与MM畅聊，请稍后~' + response.statusCode
				})
				return false
			}
		} else {
			uni.showToast({
				icon: 'none',
				title: response.errMsg
			})
			return false;
		}
	}
}

export default {
	install
}
